package com.sikadwafastdaisfondturbo.pretloan.ui.process.page

import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.ProcessCommonAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageProcessCommonBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BirthdayDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.CommonPopupWindow
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程通用列表样式
 */
class CommonPage(): ProFragment() {
    lateinit var binding: PageProcessCommonBinding
    var data: JSONObject? = null

    //内容列表
    var mCommonAdapter: ProcessCommonAdapter? = null
    var mSelectPosition = -1

    //出生日期选择
    var mBirthdayDialog: BirthdayDialog? = null

    constructor(data: JSONObject): this(){
        this.data = data
    }

    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageProcessCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRvList()
    }

    override fun initListener() {
        //下一步
        binding.btnNext.setOnClickListener {
            if (!isAllowSubmit()){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }

            val params = JSONObject().addCommonParams().apply {
                put("path",data!!.optString("apiUrl").replace("/",""))
            }
            for (i in 0..<mCommonAdapter!!.itemCount){
                val item = mCommonAdapter!!.getItem(i)
                if (item.has("selectItem")){
                    params.put(item.optString("paramName"),item.optJSONObject("selectItem").optString("value"))
                }
            }
            HHLog.e(">>>>>>提交数据>>>>>>>"+params)
            val act = context as ProcessActivity
            act.submitAction(params)

            addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_NEXT,data!!.optString("stepTitle")),"")
        }
    }

    override fun initData() {
        val dataList = arrayListOf<JSONObject>()
        val dataArray = data!!.optJSONArray("dataList")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()){
                dataList.add(dataArray.optJSONObject(i))
            }
        }
        mCommonAdapter!!.data = dataList
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRvList() {
        binding.rvCommon.setHasFixedSize(true)
        binding.rvCommon.isNestedScrollingEnabled = false
        binding.rvCommon.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvCommon.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        binding.rvCommon.addItemDecoration(LinearDecoration(0,0,0,topDecoration))
        mCommonAdapter = ProcessCommonAdapter(binding.rvCommon)
        binding.rvCommon.adapter = mCommonAdapter!!
        binding.rvCommon.itemAnimator = DefaultItemAnimator()
        mCommonAdapter!!.setOnItemChildClickListener(onItemClickListener)
    }

    /**
     * 选择
     */
    private val onItemClickListener = SikadwaOnItemChildClickListener { parent, childView, position ->
        binding.root.clearFocus()
        mSelectPosition = position
        val item = mCommonAdapter!!.getItem(position)
        when(item.optString("action")){
            "DATE_PICK" -> {//时间选择
                showBirthDialog()
            }
            "SELECT"->{//选择
                val dataList = arrayListOf<JSONObject>()
                val dataArray = item.optJSONArray("values")
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
                showSelectPopupwindow(childView,dataList)
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = CommonPopupWindow(requireContext())
        selectPopup.setWindowWidth(view.width + DensityUtils.dp2px(10f))
        selectPopup.setSelectItemListener(object : CommonPopupWindow.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                val item = mCommonAdapter!!.getItem(mSelectPosition)
                item.put("selectItem",data)
                mCommonAdapter!!.notifyItemChanged(mSelectPosition)

                addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),data!!.optString("value"))
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        selectPopup.show(view, binding.root)
        selectPopup.setBrandList(dataList)
    }

    /**
     * 选择出生日期
     */
    private fun showBirthDialog(){
        if (mBirthdayDialog == null){
            mBirthdayDialog = BirthdayDialog(context,"",object : BirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    //可根据需要自行截取数据显示
                    val item = mCommonAdapter!!.getItem(mSelectPosition)
                    val obj = JSONObject()
                    obj.put("title",selectDate.optString("showDate"))
                    obj.put("value",selectDate.optString("subDate"))
                    item.put("selectItem",obj)
                    mCommonAdapter!!.notifyItemChanged(mSelectPosition)

                    addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),selectDate.optString("subDate"))
                }
            })
        }
        mBirthdayDialog!!.show()
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        for (i in 0..<mCommonAdapter!!.itemCount){
            val item = mCommonAdapter!!.getItem(i)
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_COMMON_XX_START,data!!.optString("stepTitle")),"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_COMMON_XX_END,data!!.optString("stepTitle")),"")
    }
}